<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderNo">
        <el-input v-model="queryParams.orderNo" placeholder="请输入订单编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="业务员" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入业务员" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="queryParams.clientName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productsName">
        <el-input
          v-model="queryParams.productsName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['quotation:quote:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['quotation:quote:edit']"
        >
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['quotation:quote:remove']"
        >
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['quotation:quote:export']">
          导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="quoteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" width="80" />
      <el-table-column label="订单编号" align="center" prop="orderNo" />
      <el-table-column label="日期" align="center" prop="date" width="100" />
      <el-table-column label="业务员" align="center" prop="name" />
      <el-table-column label="客户名称" align="center" prop="clientName" :show-overflow-tooltip="true" />
      <el-table-column label="产品名称" align="center" prop="productsName" :show-overflow-tooltip="true" />
      <el-table-column label="是否新客户" align="center" prop="newClient">
        <template #default="scope">
          <dict-tag :options="yesNoOptions" :value="scope.row.newClient" />
        </template>
      </el-table-column>
      <el-table-column label="含税单价" align="center" prop="hsPrice" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['quotation:quote:edit']"
            v-if="scope.row.status === '工程审核中'"
          >
            修改
          </el-button>
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleDetail(scope.row)"
            v-hasPermi="['quotation:quote:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="danger"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['quotation:quote:remove']"
            v-if="scope.row.status === '工程审核中'"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改报价单对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="quoteForm" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNo">
              <el-input v-model="form.orderNo" placeholder="请输入订单编号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日期" prop="date">
              <el-date-picker clearable v-model="form.date" type="date" placeholder="请选择日期"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="业务员" prop="name">
              <el-input v-model="form.name" placeholder="请输入业务员" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否新客户" prop="newClient">
              <el-radio-group v-model="form.newClient">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="clientName">
              <el-input v-model="form.clientName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否需要工程审核" prop="needEngineering">
              <el-radio-group v-model="form.needEngineering">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productsName">
              <el-input v-model="form.productsName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模具" prop="mold">
              <el-input v-model="form.mold" placeholder="请输入模具" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="产品规格" prop="productsSpecification">
              <el-input v-model="form.productsSpecification" placeholder="请输入产品规格" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材料" prop="material">
              <el-input v-model="form.material" placeholder="请输入材料" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="硬度" prop="hardness">
              <el-input v-model="form.hardness" placeholder="请输入硬度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品颜色" prop="productsColor">
              <el-input v-model="form.productsColor" placeholder="请输入产品颜色" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="公差" prop="tolerance">
              <el-input v-model="form.tolerance" placeholder="请输入公差" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料号" prop="materialsNo">
              <el-input v-model="form.materialsNo" placeholder="请输入物料号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有图纸" prop="drawing">
              <el-radio-group v-model="form.drawing">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用量" prop="dosage">
              <el-input v-model="form.dosage" placeholder="请输入用量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工艺" prop="craft">
              <el-input v-model="form.craft" placeholder="请输入工艺" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="线圈" prop="coils">
              <el-input v-model="form.coils" placeholder="请输入线圈" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="切口" prop="incise">
              <el-input v-model="form.incise" placeholder="请输入切口" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="包装" prop="wrap">
              <el-input v-model="form.wrap" placeholder="请输入包装" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="交期" prop="delivery">
              <el-input v-model="form.delivery" placeholder="请输入交期" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算方式" prop="settlement">
              <el-input v-model="form.settlement" placeholder="请输入结算方式" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报价" prop="quote">
              <el-input v-model="form.quote" placeholder="请输入报价" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否有照片" prop="photo">
              <el-radio-group v-model="form.photo">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.photo">
          <el-col :span="24">
            <el-form-item label="上传图片" prop="photoUrl">
              <ImageUpload v-model="form.photoUrl" :limit="1" :fileSize="5" :isShowTip="true" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否有样品" prop="sample">
              <el-radio-group v-model="form.sample">
                <el-radio :label="true">是</el-radio>
                <el-radio :label="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="notes">
              <el-input v-model="form.notes" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报价单详情对话框 -->
    <el-dialog title="报价单详情" v-model="detailOpen" width="1000px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单编号">{{ detailForm.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="日期">{{ detailForm.date }}</el-descriptions-item>
        <el-descriptions-item label="业务员">{{ detailForm.name }}</el-descriptions-item>
        <el-descriptions-item label="是否新客户">{{ detailForm.newClient ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ detailForm.clientName }}</el-descriptions-item>
        <el-descriptions-item label="需要工程审核">{{ detailForm.needEngineering ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ detailForm.productsName }}</el-descriptions-item>
        <el-descriptions-item label="模具">{{ detailForm.mold }}</el-descriptions-item>
        <el-descriptions-item label="产品规格">{{ detailForm.productsSpecification }}</el-descriptions-item>
        <el-descriptions-item label="材料">{{ detailForm.material }}</el-descriptions-item>
        <el-descriptions-item label="硬度">{{ detailForm.hardness }}</el-descriptions-item>
        <el-descriptions-item label="产品颜色">{{ detailForm.productsColor }}</el-descriptions-item>
        <el-descriptions-item label="公差">{{ detailForm.tolerance }}</el-descriptions-item>
        <el-descriptions-item label="物料号">{{ detailForm.materialsNo }}</el-descriptions-item>
        <el-descriptions-item label="是否有图纸">{{ detailForm.drawing ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="用量">{{ detailForm.dosage }}</el-descriptions-item>
        <el-descriptions-item label="工艺">{{ detailForm.craft }}</el-descriptions-item>
        <el-descriptions-item label="线圈">{{ detailForm.coils }}</el-descriptions-item>
        <el-descriptions-item label="切口">{{ detailForm.incise }}</el-descriptions-item>
        <el-descriptions-item label="包装">{{ detailForm.wrap }}</el-descriptions-item>
        <el-descriptions-item label="交期">{{ detailForm.delivery }}</el-descriptions-item>
        <el-descriptions-item label="结算方式">{{ detailForm.settlement }}</el-descriptions-item>
        <el-descriptions-item label="报价">{{ detailForm.quote }}</el-descriptions-item>
        <el-descriptions-item label="含税单价">{{ detailForm.hsPrice }}</el-descriptions-item>
        <el-descriptions-item label="是否有照片">{{ detailForm.photo ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="产品图片" v-if="detailForm.photo && detailForm.photoUrl">
          <el-image
            style="width: 100px; height: 100px"
            :src="detailForm.photoUrl"
            :preview-src-list="[detailForm.photoUrl]"
            fit="cover"
            :initial-index="0"
            @error="() => ElMessage.error('图片加载失败')"
          />
        </el-descriptions-item>
        <el-descriptions-item label="是否有样品">{{ detailForm.sample ? '是' : '否' }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ detailForm.status }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.notes }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  listQuote,
  getQuote,
  getQuoteWithEngineering,
  addQuote,
  updateQuote,
  delQuote,
  exportQuote,
  generateOrderNo
} from '@/api/quotation/quote'
import ImageUpload from '@/components/ImageUpload/index.vue'

const { proxy } = getCurrentInstance()

// 基础路径
const baseUrl = import.meta.env.VITE_APP_BASE_API || ''

// 遮罩层
const loading = ref(false)
// 选中数组
const ids = ref([])
// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 报价单表格数据
const quoteList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 是否显示详情弹出层
const detailOpen = ref(false)

// 状态数据字典
const statusOptions = ref([
  { label: '工程审核中', value: '工程审核中' },
  { label: '财务审核中', value: '财务审核中' },
  { label: '总经理审核中', value: '总经理审核中' },
  { label: '报价审核完成', value: '报价审核完成' },
  { label: '财务反审核完成', value: '财务反审核完成' }
])

// 是否数据字典
const yesNoOptions = ref([
  { label: '是', value: true },
  { label: '否', value: false }
])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined,
  name: undefined,
  clientName: undefined,
  productsName: undefined,
  status: undefined
})

// 表单参数
const form = ref({})

// 详情表单参数
const detailForm = ref({})

// 表单校验
const rules = ref({
  date: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '业务员不能为空', trigger: 'blur' }],
  clientName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
  productsName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  productsSpecification: [{ required: true, message: '产品规格不能为空', trigger: 'blur' }]
})

/** 查询报价单列表 */
function getList() {
  loading.value = true
  listQuote(queryParams.value).then(response => {
    quoteList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    orderNo: undefined,
    date: new Date(),
    name: undefined,
    clientName: undefined,
    newClient: false,
    mold: undefined,
    productsName: undefined,
    productsSpecification: undefined,
    material: undefined,
    hardness: undefined,
    productsColor: undefined,
    tolerance: undefined,
    materialsNo: undefined,
    drawing: false,
    dosage: undefined,
    craft: undefined,
    coils: undefined,
    incise: undefined,
    wrap: undefined,
    delivery: undefined,
    settlement: undefined,
    quote: undefined,
    photo: false,
    photoUrl: undefined,
    sample: false,
    hsPrice: undefined,
    status: '工程审核中',
    needEngineering: true,
    notes: undefined,
    remark: undefined
  }
  proxy.resetForm('quoteForm')
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryForm')
  handleQuery()
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  generateOrderNo().then(response => {
    form.value.orderNo = response.data
    open.value = true
    title.value = '添加报价单'
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const id = row.id || ids.value[0]
  getQuote(id).then(response => {
    const data = response.data

    // 处理布尔值字段的回显
    if (data.newClient === 'true') {
      data.newClient = true
    } else if (data.newClient === 'false') {
      data.newClient = false
    }

    if (data.drawing === 'true') {
      data.drawing = true
    } else if (data.drawing === 'false') {
      data.drawing = false
    }

    if (data.photo === 'true') {
      data.photo = true
    } else if (data.photo === 'false') {
      data.photo = false
    }

    if (data.sample === 'true') {
      data.sample = true
    } else if (data.sample === 'false') {
      data.sample = false
    }

    // needEngineering类型转换 (tinyint->boolean)
    if (data.needEngineering === 1) {
      data.needEngineering = true
    } else if (data.needEngineering === 0) {
      data.needEngineering = false
    }

    // 处理图片URL，确保包含基础路径
    if (data.photoUrl && data.photoUrl.trim() !== '') {
      // 如果photoUrl不是以http或https开头，则添加基础路径
      if (!data.photoUrl.startsWith('http://') && !data.photoUrl.startsWith('https://')) {
        data.photoUrl = baseUrl + data.photoUrl
      }
    }

    form.value = data
    open.value = true
    title.value = '修改报价单'
  })
}

/** 查看详情按钮操作 */
function handleDetail(row) {
  getQuote(row.id).then(response => {
    const data = response.data

    // 处理布尔值字段的回显
    if (data.newClient === 'true') {
      data.newClient = true
    } else if (data.newClient === 'false') {
      data.newClient = false
    }

    if (data.drawing === 'true') {
      data.drawing = true
    } else if (data.drawing === 'false') {
      data.drawing = false
    }

    if (data.photo === 'true') {
      data.photo = true
    } else if (data.photo === 'false') {
      data.photo = false
    }

    if (data.sample === 'true') {
      data.sample = true
    } else if (data.sample === 'false') {
      data.sample = false
    }

    // needEngineering类型转换 (tinyint->boolean)
    if (data.needEngineering === 1) {
      data.needEngineering = true
    } else if (data.needEngineering === 0) {
      data.needEngineering = false
    }

    // 简单处理图片URL
    if (data.photoUrl && data.photoUrl.trim() !== '') {
      // 确保photoUrl是完整URL
      const baseUrl = import.meta.env.VITE_APP_BASE_API || ''
      if (
        !data.photoUrl.startsWith('http://') &&
        !data.photoUrl.startsWith('https://') &&
        !data.photoUrl.startsWith(baseUrl)
      ) {
        data.photoUrl = baseUrl + data.photoUrl
      }
    }

    detailForm.value = data
    detailOpen.value = true
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['quoteForm'].validate(valid => {
    if (valid) {
      // 处理布尔值转字符串
      const submitData = { ...form.value }

      // 将布尔类型转换为字符串("true"/"false")
      if (typeof submitData.newClient === 'boolean') {
        submitData.newClient = submitData.newClient.toString()
      }
      if (typeof submitData.drawing === 'boolean') {
        submitData.drawing = submitData.drawing.toString()
      }
      if (typeof submitData.photo === 'boolean') {
        submitData.photo = submitData.photo.toString()
      }
      if (typeof submitData.sample === 'boolean') {
        submitData.sample = submitData.sample.toString()
      }

      // 如果photo为false，清空photoUrl
      if (!submitData.photo || submitData.photo === 'false') {
        submitData.photoUrl = ''
      }

      // 处理photoUrl，移除基础路径前缀
      if (submitData.photoUrl && typeof submitData.photoUrl === 'string') {
        if (submitData.photoUrl.startsWith(baseUrl)) {
          submitData.photoUrl = submitData.photoUrl.replace(baseUrl, '')
        }
      }

      // 特殊处理needEngineering，需要转换为1或0(tinyint类型)
      if (submitData.needEngineering !== undefined) {
        submitData.needEngineering =
          submitData.needEngineering === true || submitData.needEngineering === 'true' ? 1 : 0
      }

      if (submitData.id != undefined) {
        updateQuote(submitData).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addQuote(submitData).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal
    .confirm('是否确认删除报价单编号为"' + _ids + '"的数据项?')
    .then(function () {
      return delQuote(_ids)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    '/quotation/quote/export',
    {
      ...queryParams.value
    },
    `quote_${new Date().getTime()}.xlsx`
  )
}

onMounted(() => {
  getList()
})
</script>
